<template>
  <div>
    <!--头文件-->
    <el-row>
      <div class="div-breadcrumb">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '' }">&#12288;&#12288;主页</el-breadcrumb-item>
          <el-breadcrumb-item>组织管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-row>
    <!--树结构-->
    <el-row>
      <el-card>
        <div
          slot="header"
          class="clearfix"
        >
          <i class="kfb-icon-yonghuzu"/>
          <span>组织机构</span>

        </div>
        <div class="block">
          <el-tree
            :data="tableData"
            :props="defaultProps"
            :expand-on-click-node="false"
            node-key="_id"
            icon="kfb-icon-yonghuzu"
          >
            <span
              slot-scope="{node, data}"
              class="custom-tree-node"
            >
              <span><i
                class="kfb-icon-yonghu">
                {{ data.name }}
              </i>
              </span>
              <span>
                <el-button
                  icon="el-icon-circle-plus-outline"
                  type="text"
                  size="mini"
                  @click="() => append(data)"
                >
                  添加
                </el-button>
                <el-button

                  v-if="isSelf(node, data)"
                  icon="el-icon-edit"
                  type="text"
                  size="mini"
                  @click="() => modify(node, data)"
                >
                  修改
                </el-button>
                <el-button
                  v-if="isSelf(node, data)"
                  icon="el-icon-remove-outline"
                  type="text"
                  size="mini"
                  @click="() => remove(node, data)"
                >
                  删除
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </el-card>
    </el-row>
    <!--编辑对话框-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="30%"
    >
      <div>
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="80px"
          label-position="right"
        >
          <el-form-item label="行政名称" size="small" prop="name">
            <el-input v-model="form.name"/>
          </el-form-item>
          <el-form-item label="匹配标识" size="small" prop="flag">
            <el-input v-model="form.flag" disabled/>
          </el-form-item>
          <el-form-item label="创建时间" size="small">
            <el-input v-model="form.ct" disabled/>
          </el-form-item>
        </el-form>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleConfirm('form')"
        >确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

  import { add, remove, update, list } from '@/api/yxwh/bmgl'
  import Clone from '@/utils/clone'

  export default {
    name: 'Index',
    data() {
      return {
        form: {},
        isAdd: false,
        tableData: [],
        rules: {
          name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
          flag: [{ required: true, message: '请输入名称', trigger: 'blur' }]
        },
        dialogVisible: false,
        selectRow: undefined,
        defaultProps: { label: 'name', children: 'children' }
      }
    },
    computed: {
      /**
       * 对话框标题
       * @returns {string}
       */
      title() {
        return this.isAdd ? '添加' : '修改'
      }

    },
    watch: {
      'form.name': function(n, o) {
        if (this.isAdd) {
          this.form.flag = this.selectRow.flag + (this.selectRow.flag.split('').reverse().join('').charAt(0) === '/' ? n : '/' + n)
        } else {
          var arr = this.selectRow.flag.split('/')
          var temp = ''
          for (let i = 0; i < arr.length - 1; i++) {
            if (arr[i] === '') continue
            temp += '/'
            temp += arr[i]
          }
          this.form.flag = temp + (this.selectRow.flag.split('').reverse().join('').charAt(0) === '/' ? n : '/' + n)
        }
      }
    },
    mounted: function() {
      /**
       * 查询
       */
      list({ dist: this.$store.getters.dept }).then(res => {
        this.tableData = res.data
      })
    },
    methods: {
      /**
       * 判断本身数据
       * @param node
       * @param data
       * @returns {boolean}
       */
      isSelf(node, data) {
        return data.flag !== this.$store.getters.dept
      },
      /**
       * 添加和修改
       */
      handleConfirm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.isAdd) {
              add(this.form).then(res => {
                this.dialogVisible = false
                this.selectRow.children.push(res.data)
              })
            } else {
              update(this.form).then(res => {
                this.dialogVisible = false
              })
            }
          }
        })
      },
      /**
       * 添加
       * @param data
       */
      append(data) {
        this.isAdd = true
        this.dialogVisible = true
        if (!data.children) {
          this.$set(data, 'children', [])
        }
        this.selectRow = data
        this.form = { name: '', flag: data.flag, children: [], pid: data._id }
      },
      /**
       * 修改
       * @param node
       * @param data
       */
      modify(node, data) {
        this.isAdd = false
        this.dialogVisible = true
        this.selectRow = data
        this.form = Clone.clone(data)
      },
      /**
       * 删除
       * @param node
       * @param data
       */
      remove(node, data) {
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          remove({ _id: data._id, pid: data.pid }).then(res => {
            const parent = node.parent
            const children = parent.data.children || parent.data
            const index = children.findIndex(d => d._id === data._id)
            children.splice(index, 1)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      /**
       * 判断时候是超级管理员
       * @returns {boolean}
       */
      isAdmin() {
        return this.$store.getters.dept === '/'
      }
    }
  }
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .kfb-icon-yonghuzu {
    margin: 0 5px 0 2px;
  }

  .div-breadcrumb {
    border-radius: 4px;
    min-height: 48px;
    background: #99a9bf;
    display: flex;
    align-items: center;
    font-size: 24px;
  }

  .el-row {
    margin-bottom: 20px;
  }

  .el-row:last-child {
    margin-bottom: 10px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both;
  }

</style>
